<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\services\IndexService;
use app\admin\validate\SetAdminPasswordValidate;
use think\App;
use think\exception\ValidateException;
use think\Request;

class Indexs extends Common
{
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->service = IndexService::getInstance();
    }

    /**
     * 主页
     *
     * @return \think\Response|\think\response\View
     */
    public function index()
    {
        return view($this->view_page, $this->service->indexs($this->admin_id));
    }

    /**
     * 编辑个人资料
     *
     * @param  \think\Request                    $request
     *
     * @return \think\response\Json|\think\response\View
     */
    public function profile(Request $request)
    {
        if ($request->isPost()){
            if ($this->service->updateAdmin($this->admin_id, $request->param())){
                return $this->successJson([], $this->service->getError());
            }else{
                return $this->errorJson($this->service->getError());
            }
        }else{
            $admin = \app\admin\model\Admins::getInstance()->detail($this->admin_id);
            return view($this->view_page, compact('admin'));
        }
    }

    /**
     * 修改登录密码
     *
     * @param  \think\Request                    $request
     *
     * @return \think\response\Json|\think\response\View
     */
    public function setPassword(Request $request)
    {
        if ($request->isPost()){
            $params = $request->param();
            try {
                validate(SetAdminPasswordValidate::class)->check($params);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return $this->errorJson($e->getMessage());
            }

            if ($this->service->setLoginAdminPassword($this->admin_id, $params)){
                return $this->successJson([], $this->service->getError());
            }else{
                return $this->errorJson($this->service->getError());
            }
        }else{
            return view($this->view_page);
        }
    }
}
